package com.lagou.component;

import com.lagou.client.RpcConsumer;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCache.StartMode;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * 注册器客户端
 *

 */
public class RegisterClient {

    /**
     * 客户端列表
     */
    private List<RpcConsumer> rpcConsumerList = new CopyOnWriteArrayList<>();

    private CuratorFramework client;

    public RegisterClient() {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        client = CuratorFrameworkFactory.builder()
                .connectString("127.0.0.1:2181")
                .sessionTimeoutMs(50000)
                .connectionTimeoutMs(30000)
                .retryPolicy(retryPolicy)
                .namespace("Register")
                .build();
        client.start();
        addListener();
    }

    /**
     * 获取客户端列表
     *
     * @return
     */
    public RpcConsumer getRpcConsumer() {
        if (rpcConsumerList.size() <= 0) {
            throw new RuntimeException("不存在注册节点");
        }

        List<RpcConsumer> sortedList = rpcConsumerList.stream().sorted(new Comparator<RpcConsumer>() {
            @Override
            public int compare(RpcConsumer o1, RpcConsumer o2) {
                return (int) (o1.getLastResponseTimeSpan() - o2.getLastResponseTimeSpan());
            }
        }).collect(Collectors.toList());
        return sortedList.get(0);
    }

    /**
     * 增加节点监听器
     */
    private void addListener() {
        String path = "/ServerBootstrap";
        PathChildrenCache pathChildrenCache = new PathChildrenCache(client, path, true);
        try {
            pathChildrenCache.start(StartMode.POST_INITIALIZED_EVENT);
            pathChildrenCache.getListenable().addListener(
                    new PathChildrenCacheListener() {
                        @Override
                        public void childEvent(CuratorFramework curatorFramework,
                                               PathChildrenCacheEvent pathChildrenCacheEvent) throws Exception {
                            switch (pathChildrenCacheEvent.getType()) {
                                case CHILD_ADDED:
                                case CHILD_REMOVED:
                                case CHILD_UPDATED:
                                case INITIALIZED:
                                    updateRpcConsumerList();
                            }
                        }
                    }
            );
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新注册的节点列表
     */
    private void updateRpcConsumerList() {
        String path = "/ServerBootstrap";
        List<String> children = null;
        try {
            children = client.getChildren()
                    .forPath(path);
        } catch (Exception e) {
            e.printStackTrace();
        }

        rpcConsumerList.forEach(rpcConsumer -> {
            rpcConsumer.shutdown();
        });
        rpcConsumerList.clear();

        if (children != null && children.size() > 0) {
            children.forEach(node -> {
                try {
                    byte[] bytes = client.getData().forPath(path + "/" + node);
                    String address = new String(bytes);
                    System.out.println("获取注册地址信息：" + address);
                    String[] split = address.split(":");
                    RpcConsumer rpcConsumer = new RpcConsumer(split[0], Integer.parseInt(split[1]));
                    rpcConsumerList.add(rpcConsumer);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
    }

}
